//
//  LEEPictureView.swift
//  SinaWeibo
//
//  Created by 李江波 on 2016/11/16.
//  Copyright © 2016年 lijiangbo. All rights reserved.
//

import UIKit

private let cell_ID = "LEEPicCollectionCell_ID"

class LEEPictureView: UICollectionView {

    var items : [LEEPic_url]? {
    
        didSet{
        
            self.reloadData()
        }
    }
    
   
    override func awakeFromNib() {
        super.awakeFromNib()
        
        self.dataSource = self
        self.delegate = self
        
        let nib = UINib(nibName: "LEEPicCollectionCell", bundle: nil)
        
        self.register(nib, forCellWithReuseIdentifier: cell_ID)
        
    }

}


// MARK: - UICollectionViewDataSource
extension LEEPictureView : UICollectionViewDataSource,UICollectionViewDelegate {

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return items?.count ?? 0
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cell_ID, for: indexPath) as! LEEPicCollectionCell
        
        let urlStr = items![indexPath.item]
        
        cell.picUrl = urlStr
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        //显示图片浏览器
        
        /*
         @property (nonatomic, weak) UIView *sourceImagesContainerView;
         @property (nonatomic, assign) NSInteger currentImageIndex;
         @property (nonatomic, assign) NSInteger imageCount;
         
         @property (nonatomic, weak) id<SDPhotoBrowserDelegate> delegate;
         
         - (void)show;
         */
        
        //1. 实例化图片浏览器对象
        let browser = SDPhotoBrowser()
        
        browser.sourceImagesContainerView = self
        browser.currentImageIndex = indexPath.item
        browser.imageCount = items?.count ?? 0
        
        browser.delegate = self
        
        browser.show()
        
    }

}

extension LEEPictureView : SDPhotoBrowserDelegate {
    //返回高质量图片的url对象
    func photoBrowser(_ browser: SDPhotoBrowser!, highQualityImageURLFor index: Int) -> URL! {
      
        let picinfo = items![index]
        let url = URL(string: picinfo.bimiddleImage!)
        
        return url
    }
    
    //返回一个占位的图片
    func photoBrowser(_ browser: SDPhotoBrowser!, placeholderImageFor index: Int) -> UIImage! {
       
        let indexPath = IndexPath(item: index, section: 0)
        let cell = self.cellForItem(at: indexPath) as! LEEPicCollectionCell
        
        return cell.pic_item.image
    }
}





